package com.offcn.servlet;

import com.offcn.bean.Course;
import com.offcn.service.CourseService;
import com.offcn.service.Impl.CourseServiceImpl;
import com.offcn.utils.*;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.IOException;
import java.util.Locale;

@WebServlet(name = "CourseServlet", urlPatterns = {"/CourseServlet"})
@MultipartConfig
public class CourseServlet extends BaseServlet {

    private ReturnResult returnResult = null;
    private CourseService courseService=new CourseServiceImpl();

    //文件删除的方法
    protected void doDelfile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String fileName = request.getParameter("fileName");

        File file = new File("/Users/lazy-bay/Desktop/JAVA/myedutest/eduFile/" + fileName);
        boolean delete = file.delete();
        int i = 0;
        while (!delete) {
            delete = file.delete();
            i++;
            if (i > 10) {
                break;
            }
        }
        //对文件进行 查判断 他是视频 哈市照片
        String houzhim = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        if (houzhim.equals("mp4")) {
            returnResult = new ReturnResult("视频删除成功", 2, null);
        } else {
            returnResult = new ReturnResult("照片删除成功", 1, null);
        }
        ObjectJsonUtil.objOrJson(returnResult, response);
    }

    //文件上传
    protected void douploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Part part = request.getPart("file");
        String fileName = FileUploadUtils.uploadPic(part);

        //根据文件名 判断 文件上传是否成功
        String name = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        if ("mp4".equals(name)){
            fileName = "http://localhost:8080/eduFile/" + fileName;

            returnResult=new ReturnResult("视频上传成功",2,fileName);
        }else {
            fileName = "http://localhost:8080/eduFile/" + fileName;
            returnResult=new ReturnResult("图片上传成功",1,fileName);
        }
        ObjectJsonUtil.objOrJson(returnResult, response);
    }

    //进行分页查询
    protected void getCourseListPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pageSize = request.getParameter("pageSize");
        String pageNo = request.getParameter("pageNo");
        String cname = request.getParameter("cname");
        Page<Course> page = courseService.getCourseListPage(pageSize, pageNo, cname);
        if (page.getList()!=null&&page.getList().size()>0){
            returnResult = new ReturnResult("", 1, page);
        }else {
            returnResult = new ReturnResult("", -1, null);
        }
        ObjectJsonUtil.objOrJson(returnResult, response);
    }


}
